package main

import (
	"fmt"
)

//

//A找到第一个等于3的
//B找到最后一个等于3
//C找到第一个大于等于2
//D找到最后一个小于7的数据
//arr:=[]int {1,2,3,3,4,5,6,6,6,6,7,9,10}

func main() {

	arr := []int{1, 2, 3, 3, 3, 3, 3, 4, 5, 6, 6, 6, 6, 7, 9, 10}
	for i := 0; i < len(arr); i++ {

		fmt.Println("index", i, arr[i])
	}

	// fmt.Println(bin_searchA(arr, 3))  //找到第一个等于3的
	// fmt.Println(bin_searchB(arr, 3)) //查找最后一个等于3的

	// fmt.Println(bin_searchC(arr, 6)) // 找到第一个大于等于6

	fmt.Println(bin_searchD(arr, 6)) // 找到最后一个小于6的
}

//  找到最后一个小于6的
func bin_searchD(arr []int, val int) int {
	left := 0
	right := len(arr) - 1
	index := -1 // 查找元素的下标
	for left <= right {
		mid := (left + right) / 2

		fmt.Println(left, right, mid)

		if arr[mid] >= val {

			right = mid - 1

		} else {
			// index = mid
			// break

			if mid == 0 || arr[mid+1] >= val {
				index = mid
				break
			} else {

				// right = mid - 1
				left = mid + 1
			}
		}

	}
	return index
}

// 找到第一个大于等于6
func bin_searchC(arr []int, val int) int {
	left := 0
	right := len(arr) - 1
	index := -1 // 查找元素的下标
	for left <= right {
		mid := (left + right) / 2

		fmt.Println(left, right, mid)

		if arr[mid] < val {
			// right = mid - 1
			left = mid + 1
		} else {
			// index = mid
			// break

			if mid == len(arr)-1 || arr[mid-1] < val {
				index = mid
				break
			} else {

				right = mid - 1
			}
		}

	}
	return index
}

//找到第一个等于3的
func bin_searchA(arr []int, val int) int {
	left := 0
	right := len(arr) - 1
	index := -1 // 查找元素的下标
	for left <= right {
		mid := (left + right) / 2

		fmt.Println(left, right, mid)

		if arr[mid] < val {

			left = mid + 1
		} else if arr[mid] > val {
			right = mid - 1
		} else {
			// index = mid
			// break

			if mid == 0 || arr[mid-1] != val {
				index = mid
				break
			} else {
				right = mid - 1
			}
		}

	}
	return index
}

// B找到最后一个等于3
func bin_searchB(arr []int, val int) int {
	left := 0
	right := len(arr) - 1
	index := -1 // 查找元素的下标
	for left <= right {
		mid := (left + right) / 2

		fmt.Println(left, right, mid)

		if arr[mid] < val {

			left = mid + 1
		} else if arr[mid] > val {
			right = mid - 1
		} else {
			// index = mid
			// break

			if mid == 0 || arr[mid+1] != val {
				index = mid
				break
			} else {
				left = mid + 1
				//index = mid
			}
		}

	}
	return index
}
